using System.Threading.Tasks;
using ENode.Commanding;
using ENode.Infrastructure;
using ENodeMicro.Commands.Members;
using ENodeMicro.Domain.Members.Services;

namespace ENodeMicro.CommandHandlers
{
    /// <summary>
    /// 会员命令处理程序
    /// </summary>
    public class MemberCommandHandler :
        ICommandHandler<CreateMemberWithPhoneNumberCommand>
    {
        private readonly ILockService _lockService;
        private readonly MemberService _service;

        public MemberCommandHandler(ILockService lockService, MemberService service)
        {
            _lockService = lockService;
            _service = service;
        }
        /// <summary>
        /// 创建会员命令
        /// </summary>
        /// <param name="context"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task HandleAsync(ICommandContext context, CreateMemberWithPhoneNumberCommand command)
        {
            await _lockService.ExecuteInLock(nameof(Domain.Members.Member), async () =>
            {
                await _service.CheckPhoneNumberForCreate(command.PhoneNumber);
            });

            await context.AddAsync(new Domain.Members.Member(command.AggregateRootId, command.PhoneNumber));
        }
    }
}